package com.zust.data.web.rest;

import com.zust.data.dto.ResponseDto;
import com.zust.data.dto.SessionInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;

/**
 * @author senselyan
 * @Description:
 * @date 2018/5/9 10:11
 */
@RestController
@RequestMapping("/file")
public class FileResource {

    @Value("${upload.file.location}")
    private String uploadLocation;

    @RequestMapping("/upload")
    public ResponseDto upload(@RequestParam("file") MultipartFile file, HttpSession session, HttpServletRequest request) {
        if (!file.isEmpty()) {

                SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
                String fileBasePath =
                        ClassUtils.getDefaultClassLoader().getResource("").getPath();
                String fileRelaPath = "/static/images/icon/" + sessionInfo.getId() + ".jpg";
                String filePath = uploadLocation + fileRelaPath;
                String filePathMirror = fileBasePath + fileRelaPath;
                File dest = new File(filePath);
                File destMirror = new File(filePathMirror);
            try {

                // 检测是否存在目录
                if (!dest.exists()) {
                    dest.getParentFile().mkdirs();// 新建文件夹
                    dest.createNewFile();
                }
                file.transferTo(dest);// 文件写入

//                Files.copy(destMirror.toPath(), dest.toPath());
//                Files.copy(dest.toPath(), destMirror.toPath());

                //服务器缓存文件
                if (!destMirror.exists()) {
                    destMirror.getParentFile().mkdirs();
                    dest.createNewFile();
                }
                file.transferTo(destMirror);

                return new ResponseDto(true, "上传成功", fileRelaPath);
            } catch (FileNotFoundException exp) {
                return new ResponseDto(true, "上传成功", fileRelaPath);
            } catch (Exception e) {
                e.printStackTrace();
                return new ResponseDto(false, "上传失败");
            }
        } else {
            return new ResponseDto(false, "文件为空");
        }


    }
}
